package comman.duke 
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	/**
	 * ...
	 * @author jerry.d
	 */
	public class ShakeMgr 
	{
		public static const SHAKE_HOR:int = 0;
		public static const SHAKE_VER:int = 1;
		public static const SHAKE_TWIST:int = 2;
		private var shakeItems:Vector.<ShakeItem>;
		private var frameItem:FrameItem;
		private var name:String;
		public function ShakeMgr(){
			this.shakeItems = new Vector.<ShakeItem>();
			name  = "shakemgr";
			frameItem = new FrameItem(name, onEnterFrame);
		}
		/**
		 * {id:IHashId,dis:DisplayObject,offx:number,offy:number}
		 * **/
		 public function addShakeItem(item:ShakeItem){
			if( this.shakeItems.indexOf(item) != -1)
			{
				this.removeShakeItem(item);
			}
			item.gap =  item.gap || 5;//distance each shake
			item.cnt = item.cnt || 5;//times

			this.shakeItems.push(item);
			if( !FrameMgr.Instance.has(name) ){
				FrameMgr.Instance.add(frameItem);
			}
		}
		private var gap:int = 3;
		private function onEnterFrame(delta:int):void{
			this.gap--;
			if( this.gap == -1){
				var obj:Object;
				var dis:DisplayObject;
				var shakeType:int;
				for each(var item:ShakeItem in shakeItems){
					dis = item.display;
					shakeType = item.type;
					if(shakeType == SHAKE_HOR)
					{
						if( item.cnt == 0){
							this.removeShakeItem(item);
							dis.x = obj.ox;
						}else{
							item.cnt--;
							if( item.cnt%2 == 0){
								dis.x = item.ox + item.gap;
							}else{
								dis.x = item.ox - obj.gap;
							}
						}
					}else if(shakeType == SHAKE_VER)
					{
						if( item.cnt == 0){
							this.removeShakeItem(item);
							dis.y = item.oy;
						}else{
							item.cnt--;
							if( item.cnt%2 == 0){
								dis.y = item.oy+item.gap;
							}else{
								dis.y = item.oy-item.gap;
							}
						}
					}else if(shakeType == SHAKE_TWIST){
						if( item.cnt == 0){
							this.removeShakeItem(item);
							dis.rotation = 0;
						}else{
							item.cnt--;
							if(item.cnt%2 == 0){
								dis.rotation = item.gap;
							}else{
								dis.rotation = -item.gap;
							}
						}
					}

				}
				this.gap = 3;
				if( shakeItems.length == 0 ){
					FrameMgr.Instance.remove(this.name);
				}
			}

		}

		public function removeShakeItem(item:ShakeItem):void{
			var index:int = shakeItems.indexOf(item);
			if ( index == -1 ) return;
			item.reset();
			this.shakeItems.splice(index, 1);
			PoolMgr.reclaim(item);
		}

		public function pause():void{
			FrameMgr.Instance.remove(this.name);
		}

		public function resume():void{
			FrameMgr.Instance.add(this.frameItem);
		}

		public function reset():void {
			for each(var item:ShakeItem in this.shakeItems){
				this.removeShakeItem(item);
			}
			FrameMgr.Instance.remove(this.name);
		}
		
		private static var _instance:ShakeMgr;
		public static function get Instance():ShakeMgr{
			if(ShakeMgr._instance == null)
				ShakeMgr._instance = new ShakeMgr();

			return ShakeMgr._instance;
		}
		
	}

}